/*
 * @lc app=leetcode.cn id=114 lang=javascript
 *
 * [114] 二叉树展开为链表
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    let list=[]
    let helper=function(node){
        if(!node)return
        list.push(node)
        helper(node.left)
        helper(node.right)
    }
    helper(root)
    let len=list.length
    for(let i=0;i<len-1;i++){
        let pre=list[i]
        let curr=list[i+1]
        pre.left=null
        pre.right=curr
    }
    return root
};
// @lc code=end

function TreeNode(val, left, right) {
       this.val = (val===undefined ? 0 : val)
       this.left = (left===undefined ? null : left)
      this.right = (right===undefined ? null : right)
     }
let a={
    val:1,
    left:{
        val:2,
        left:{
            val:3,
            left:null,
            right:null
        },
        right:{
            val:4,
            left:null,
            right:null
        }
    },
    right:{
        val:5,
        left:null,
        right:{
            val:6,
            left:null,
            right:null
        }
    }
}
var flatten = function(root) {
    let node=new TreeNode(0)
    let fakeHead=node
    let helper=function(root){
        if(!root)return 
        let val=root.val
        node.right=new TreeNode(val)
        node=node.right
        helper(root.left)
        helper(root.right)
    }
    helper(root)
    return fakeHead.right
};//非原地改变版